package com.geekhalo.lego.plugin.readfrom;


import com.geekhalo.lego.plugin.support.action.BaseAnAction;
import com.intellij.ide.util.ClassFilter;
import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.UndoUtil;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;

public class CreateReadFromAction extends BaseAnAction {


    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        PsiClass targetPsiClass = getJavaClass(e);

        if (targetPsiClass == null){
            Messages.showMessageDialog("请选择", "Warn", null);
            return;
        }

        TreeClassChooserFactory factory = TreeClassChooserFactory.getInstance(e.getProject());
        // 设置过滤条件，只选择 public 类型的类
        ClassFilter classFilter = psiClass -> psiClass.getModifierList().hasExplicitModifier(PsiModifier.PUBLIC);
        // 弹出选择类的窗口
        TreeClassChooser chooser = factory.createWithInnerClassesScopeChooser(
                "选择类型",
                GlobalSearchScope.allScope(e.getProject()),
                classFilter,
                null);
        chooser.showDialog();
        // 获取用户选择的类
        PsiClass fromPsiClass = chooser.getSelected();
        // 如果用户选择了类，则在控制台输出类名
        if (fromPsiClass != null) {
            String methodStr = CreateReadFromMethod.create(e.getProject(), fromPsiClass, targetPsiClass);
            Editor editor = e.getData(PlatformDataKeys.EDITOR);
            Document document = editor.getDocument();

            int offset = editor.getCaretModel().getOffset();

            WriteCommandAction.runWriteCommandAction(e.getProject(), ()->{
                document.insertString(offset, methodStr);

                UndoUtil.markPsiFileForUndo(e.getData(LangDataKeys.PSI_FILE));
            });
        }
    }

}
